#!/bin/bash

spec=$1

single_merge() {
    awk -v key="$1" -v max_len=80 -F : \
    'BEGIN {\
        tmp="";\
    } \
    {\
        if (key == $1) {\
            if (NF > 2) {\
                oofs=FS;FS="#";
                bbb=sub(/[[:alnum:]]+:/,"",$0);\
                aaa=$bbb;
                FS=oofs;
            } else {\
                $1=""; \
                aaa=$0;\
            }\

            tmp1=tmp aaa
            gsub(" +"," ",tmp1);\
            #print FNR tmp1
            if (length(tmp1) > max_len) {\
                gsub(" +"," ",tmp);\
                printf "%-20s%s\n",key ":",tmp;\
                tmp="";\
            }\
            tmp=tmp aaa;\
        } else {\
            if (length(tmp) != 0) {\
                gsub(" +"," ",tmp);\
                printf "%-20s%s\n",key ":",tmp;\
                tmp="";\
            }\
            print $0;\
        }\
    }'
}

convert_doc() {
    sed -i 's/%package\s\+javadoc/%package help/g' $spec
    sed -i '/%description\s\+javadoc/i\Provides: %{name}-javadoc = %{version}-%{release}' $spec
    sed -i '/%description\s\+javadoc/i\Obsoletes: %{name}-javadoc < %{version}-%{release}' $spec
    sed -i 's/%description\s\+javadoc/%description help/g' $spec
    sed -i 's/%files\s\+javadoc/%files help/g' $spec
    sed -i 's/%package\s\+doc/%package help/g' $spec
    sed -i '/%description\s\+doc/i\Provides: %{name}-doc = %{version}-%{release}' $spec
    sed -i '/%description\s\+doc/i\Obsoletes: %{name}-doc < %{version}-%{release}' $spec
    sed -i 's/%description\s\+doc/%description help/g' $spec
}

headers_merge() {
    cat $spec | single_merge "Provides" | single_merge "Obsoletes" > .$spec
    mv -f .$spec $spec
}

if [ -f $spec ]; then
    convert_doc
    headers_merge
else
    echo "Usage: script SPECFILE"
fi

